package etnorservice.etnor_service.utils;


import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * HTTP请求工具类
 */
public class HttpUtil {

    private static final RestTemplate restTemplate = new RestTemplate();

    /**
     * 发送GET请求
     * @param url 请求URL
     * @param params 查询参数
     * @return 响应结果
     */
    public static String sendGetRequest(String url, Map<String, String> params) {
        StringBuilder sb = new StringBuilder(url);
        if (params != null && !params.isEmpty()) {
            sb.append("?");
            params.forEach((key, value) -> sb.append(key).append("=").append(value).append("&"));
            sb.setLength(sb.length() - 1); // 去掉最后一个&
        }

        ResponseEntity<String> response = restTemplate.getForEntity(sb.toString(), String.class);

        return response.getBody();
    }

    /**
     * 发送POST请求
     * @param url 请求URL
     * @param params 表单参数
     * @return 响应结果
     */
    public static String sendPostRequest(String url, Map<String, String> params) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/x-www-form-urlencoded");

        HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(params, headers);

        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
        return response.getBody();
    }
}
